﻿using Eholly.Database;
using Eholly.Database.Ef;
using Eholly.Hosting;
using Eholly.Logger;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eholly.Framework.Database.Ef.Sqlite.Test
{
    public partial class MainForm : Form
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IRepository<DataTransferRecordEntity, long> _requestLogRepository;
        private readonly IRepository<ApiRequestRecordEntity, long> _apiRequestRecordRepository;
        private readonly IAppHost _appHost;
        public MainForm(
            IAppHost appHost,
            IUnitOfWork unitOfWork,
            IRepository<DataTransferRecordEntity, long> requestLogRepository,
            IRepository<ApiRequestRecordEntity, long> apiRequestRecordRepository,
            ILoggerManager loggerManager,
            IConfiguration configuration,
            HostConfiguration hostConfiguration)
        {
            _appHost = appHost;
            _unitOfWork = unitOfWork;
            _requestLogRepository = requestLogRepository;
            _apiRequestRecordRepository = apiRequestRecordRepository;

            InitializeComponent();
        }

        /// <summary>
        /// 增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button1_Click(object sender, EventArgs e)
        {
            var insertEntity = await _requestLogRepository.InsertAsync(new DataTransferRecordEntity
            {
                ErrorMessage = "错误消息",
                CreationTime = StandardTime.Now,
                DurationTotalMilliseconds = 100,
                RecordType = 2,
                HandleStatus = 1,
                Data = "json数据包",
                StartTime = StandardTime.Now.AddSeconds(-2),
                EndTime = StandardTime.Now,
                Summary = "百度回发了错误信息",
            });
            Debug.WriteLine($"刚插入的实体类的所产生的主键ID是：{insertEntity.Id}");

            //var insertEntityId = await _requestLogRepository.InsertAndGetIdAsync(new DataTransferRecordEntity
            //{
            //    ErrorMessage = "错误消息",
            //    IsSuccess = false,
            //    JsonData = "json数据包",
            //    RequestUri = "https://baidu.com",
            //    ResponseData = "百度回发了错误信息"
            //});
            //Debug.WriteLine($"刚插入的实体类的所产生的主键ID是：{insertEntityId}");

            var result = await _requestLogRepository.SaveChangesAsync();
        }
        /// <summary>
        /// 循环增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    try
                    {
                        _ = ExecuteAsync();
                    }
                    catch (System.Exception exp)
                    {
                        Debug.WriteLine("增的时候出错：\r\n" + exp);
                    }

                    await Task.Delay(1);
                }
            });
        }
        private readonly AsyncLock dbContextLock = new AsyncLock();

        private async Task ExecuteAsync()
        {
            Random random = new Random();
            if (random.Next(1, 100) > 50)
            {
                //var provider = _appHost.ServiceProvider.GetRequiredService<IDbContextProvider<TestSqlSugarDbContext>>();
                //var apiRequestRecordRepository = new EfRepository<TestSqlSugarDbContext, ApiRequestRecordEntity, long>(provider);

                var entity = new ApiRequestRecordEntity
                {
                    ReceiveData = "收到的数据",
                    SendData = "发送的数据",
                    Msg = "错误信息",
                    ReturnCode = "200",
                    Name = "Api名称",
                    RequestAddress = "http://baidu.com"
                };


                //var insertEntity = apiRequestRecordRepository.GetDbContext().Set<ApiRequestRecordEntity>().Add(entity);
                //await apiRequestRecordRepository.GetDbContext().SaveChangesAsync();

                using (await dbContextLock.LockAsync("id1"))
                {
                    var insertEntity = await _apiRequestRecordRepository.InsertAsync(entity);
                    await _apiRequestRecordRepository.SaveChangesAsync();
                    Debug.WriteLine($"刚插入的实体类的所产生的主键ID是：{insertEntity.Id}");
                }
            }
        }

        /// <summary>
        /// 删
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            _requestLogRepository.Delete(1);
            _requestLogRepository.Delete(7);
            _requestLogRepository.SaveChanges();
        }

        /// <summary>
        /// 改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button3_Click(object sender, EventArgs e)
        {
            var entity1 = await _requestLogRepository.FirstOrDefaultAsync(q => q.Id == 8);
            entity1.ErrorMessage = "marc";
            var entity2 = await _requestLogRepository.UpdateAsync(entity1);
            await _requestLogRepository.SaveChangesAsync();
        }

        /// <summary>
        /// 查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            var entity1 = _requestLogRepository.FirstOrDefault(q => q.Summary == "百度");
            var entity2 = _requestLogRepository.FirstOrDefault(q => q.RecordType > 0);
        }

        /// <summary>
        /// 循环查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    try
                    {
                        using (await dbContextLock.LockAsync("id1"))
                        {
                            var date = DateTime.Now.AddDays(-1);
                            var count = _apiRequestRecordRepository
                            .GetAll()
                            .OrderByDescending(q => q.CreationTime)
                            .Where(q => q.CreationTime >= date)
                            .Count();
                            Debug.WriteLine($"数量：{count}");
                        }
                    }
                    catch (System.Exception exp)
                    {
                        Debug.WriteLine("查的时候出错：\r\n" + exp);
                    }
                    await Task.Delay(10);
                }
            });
        }

        /// <summary>
        /// 事务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button7_Click(object sender, EventArgs e)
        {
            try
            {
                _unitOfWork.BeginTransaction();

                var result = await _requestLogRepository.InsertAsync(new DataTransferRecordEntity
                {
                    ErrorMessage = "错误消息",
                    CreationTime = StandardTime.Now,
                    DurationTotalMilliseconds = 100,
                    RecordType = 2,
                    HandleStatus = 1,
                    Data = "json数据包",
                    StartTime = StandardTime.Now.AddSeconds(-2),
                    EndTime = StandardTime.Now,
                    Summary = "百度回发了错误信息",
                });

                var entity = await _requestLogRepository.FirstOrDefaultAsync(q => true);
                if (entity == null)
                {
                    Debug.WriteLine("无数据，无法演示修改");
                    _unitOfWork.Rollback();
                    return;
                }
                entity.ErrorMessage = "马志远事务成功了";
                await _requestLogRepository.UpdateAsync(entity);

                await _unitOfWork.SaveChangesAsync();

                _unitOfWork.Commit();
            }
            catch (Exception ex)
            {
                _unitOfWork.Rollback();
                Debug.WriteLine("发生错误: " + ex.Message);

            }
        }

        /// <summary>
        /// 大批量删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Restart();
            //_apiRequestRecordRepository.Delete(q => true);
            //_apiRequestRecordRepository.SaveChanges();

            var context = ((IRepositoryWithDbContext)_apiRequestRecordRepository).GetDbContext() as TestSqliteDbContext;
            context.Database.ExecuteSqlCommand("delete from ApiRequestRecords;");
            context.SaveChanges();

            stopwatch.Stop();

            MessageBox.Show($"耗时：{stopwatch.ElapsedMilliseconds}");
        }
    }
}
